var Menu = function(){
	var ztreeObj = null;
	var moduleValidator = null,menuValidator = null;
	//刷新树
	function initMenuTree(id){
		SysMenuController.getTreeByAppId(null,null,function(trees){
			ZtreeUtil.initTree("ztree",trees,{
				onClick:function(event, treeId, treeNode){
					if(treeNode.type == "module"){
						moduleInfoView(treeNode.id);
					}else if(treeNode.type=="menu"){
						menuInfoView(treeNode.id);
					}
				},
				beforeClick:function(treeId, treeNode, clickFlag){
					if(treeNode.type == "module" || treeNode.type=="menu"){
						return true;
					}else{
						return false;
					}
				}
				
			},{
				data:{
					key:{
						name: "text",
		    			url: null
					}
				},
				view: {
					fontCss: function(treeId, treeNode) {
						if(treeNode.attributs){
							return treeNode.attributs.hide? {color:"#808080"} : {};
						}
					}
				}
			},{
				context:[{
	                id: "addModule",
	                label: "新增模块",
	                visible:function(NODE,TREE_OBJ){
	                	if(NODE.type=="app"){
	                		return true;
	                	}else{
	                		return false;
	                	}
	                },
	                action: function(NODE, TREE_OBJ){
//	                	$('#officeContent').attr("src",contextPath+"/sys/module/edit.htm?appId="+NODE.id);
	                	initTabStatus("module-info-edit","新增模块");
	                	AppUtils.clearForm("#editModuleForm");
	                	AppUtils.validatorRemoteCache("#editMoudel_name");
	                	$("#editMoudel_appId").val(NODE.id);
	                	
	                }
	            }, {
	                id: "addMenu",
	                label: "新增菜单",
	                visible: function(NODE,TREE_OBJ){
	                	if(NODE.type=="module"){
	                		return true;
	                	}else{
	                		return false;
	                	}
	                },
	                action: function(NODE, TREE_OBJ){
//	                	$('#officeContent').attr("src",contextPath+"/sys/menu/edit.htm?moduleId="+NODE.id);
	                	initTabStatus("menu-info-edit","新增菜单");
	                	AppUtils.clearForm("#editMenuForm");
	                	AppUtils.validatorRemoteCache("#editMenu_name");
	                	$("#editMenu_moduleId").val(NODE.id);
	                }
	            },{
	                id: "delModule",
	                label: "删除模块",
	                visible: function(NODE,TREE_OBJ){
	                	if(NODE.type=="module"){
	                		return true;
	                	}else{
	                		return false;
	                	}
	                },
	                action: function(NODE, TREE_OBJ){
	                	var message = "";
	                	if(NODE.isParent){
	                		message ="该模块下存在菜单<br>"
	                	}
	                	Message.confirm(message+'确认删除模块【'+NODE.text+'】吗？', function(index){
	    					SysModuleController.deleteModuleById(NODE.id,function(value){
	        					if(value){
	        						Message.success('删除成功');
	        						ZtreeUtil.removeNodeRefreshTree('ztree',NODE);
	        					}else{
	        						Message.error('删除失败');
	        					}
	        					Message.close(index); 
	        				});
	                       
	                    });
	                }
	            },{
	                id: "delMenu",
	                label: "删除菜单",
	                visible: function(NODE,TREE_OBJ){
	                	if(NODE.type=="menu"){
	                		return true;
	                	}else{
	                		return false;
	                	}
	                },
	                action: function(NODE, TREE_OBJ){
	                	Message.confirm('确认删除菜单【'+NODE.text+'】吗？', function(index){
	        				SysMenuController.deleteMenuById(NODE.id,function(value){
	        					if(value == "success"){
	        						Message.success('删除成功');
	        						ZtreeUtil.removeNodeRefreshTree('ztree',NODE);
	        					}else{
	        						Message.error('删除失败');
	        					}
	        					Message.close(index); 
	        				});
	                       
	                    });
	                }
	            }]
			});
			ztreeObj = ZtreeUtil.getZtreeObj('ztree');
			if(id){
				//保持选中前状态
				var node = ztreeObj.getNodeByParam("id",id);
				ztreeObj.selectNode(node);
			}
		});
		
	}
	
	function initTabStatus(id,text){
		$("#module-info-view").hide();
		$("#module-info-edit").hide();
		$("#menu-info-view").hide();
		$("#menu-info-edit").hide();
		if(id){
			$("#"+id).show();
			$("#"+id).find(".ui-widget-header").text(text);
		}
		
		
	}
		
	function moduleInfoView(moduleId){
		initTabStatus("module-info-view");
//		$('#officeContent').attr("src",contextPath+"/sys/module/view.htm?moduleId="+treeNode.id);
		SysModuleController.getModuleInfoById(moduleId,function(moduleInfo){
			$.each(moduleInfo, function(key, value) {
				if($("#viewMoudel_"+key).length){
					dwr.util.setValue('viewMoudel_' + key, value);
				}
			});
		});
	}
	function menuInfoView(menuId){
		initTabStatus("menu-info-view");
		SysMenuController.getMenuInfoById(menuId,function(menuInfo){
			$.each(menuInfo, function(key, value) {
				if($("#viewMenu_"+key).length){
					if(key == "icon"){
						$("#viewMenu_icon").find("i").attr("class",value);
					}else if(key == "display"){
						$('#viewMenu_'+ key).text(value=='1'?'显示':'隐藏');
					}else{
						dwr.util.setValue('viewMenu_' + key, value);
					}
					
				}
			});
		});
	}
	function updateIconText(index,layero){
		var body = DialogUtils.getChildFrame('body', index);
		var icon = body.find("#icon").val();
		$("#editMenu_icon").val(icon);
		$("#edit_icon").find("i").attr("class",icon);
		DialogUtils.close(index);
	}
	return {
		initMenuPage:function(){
			initMenuTree();
			moduleValidator=$("#editModuleForm").validate({
				onkeyup: function(element, event){
					if ($(element).attr('name') == "editMoudel_name") {
                        return false; 
                    } else { 
                        if ( event.which === 9 && this.elementValue( element ) === "" ) {
                            return;
                        } else if ( element.name in this.submitted || element === this.lastElement ) {
                            this.element( element );
                        }
                    }
				},
				rules:{
					editMoudel_name:{required:true,maxlength:8,remote:{
						url:contextPath+'/sys/module/checkNameISExist.htm',
						type:'post',
						cache:false,
						dataType:'json',
						data:{
							id:function(){
								return $("#editMoudel_id").val();
							},
							appId:function(){
								return $("#editMoudel_appId").val();
							}
						}
					}},
					editMoudel_sort:{required:true,maxlength:3,digits:true}
				},
				messages:{
					editMoudel_name:{remote:jQuery.format("模块名称【{0}】已经存在")}
				}
			});
			menuValidator=$("#editMenuForm").validate({
				onkeyup: function(element, event){
					if ($(element).attr('name') == "editMenu_name") {
                        return false; 
                    } else { 
                        if ( event.which === 9 && this.elementValue( element ) === "" ) {
                            return;
                        } else if ( element.name in this.submitted || element === this.lastElement ) {
                            this.element( element );
                        }
                    }
				},
				rules:{
					editMenu_name:{required:true,maxlength:8,remote:{
						url:contextPath+'/sys/menu/checkNameISExist.htm',
						type:'post',
						cache:false,
						dataType:'json',
						data:{
							id:function(){
								return $("#editMenu_id").val();
							},
							moduleId:function(){
								return $("#editMenu_moduleId").val();
							}
						}
					}},
					editMenu_sort:{required:true,maxlength:3,digits:true},
					editMenu_url:{required:true}
				},
				messages:{
					editMenu_name:{remote:jQuery.format("菜单名称【{0}】已经存在")}
				}
			});
		},
		refreshTree:function(){
			initMenuTree();
		},
		loadModuleInfo4Edit:function(moduleId){
			AppUtils.validatorRemoteCache("#editMoudel_name");
			SysModuleController.getModuleInfoById(moduleId,function(moduleInfo){
				if(moduleInfo){
					initTabStatus("module-info-edit","修改模块");
					AppUtils.clearForm("#editModuleForm");
					$.each(moduleInfo, function(key, value) {
						if($("#editMoudel_"+key).length){
							dwr.util.setValue('editMoudel_' + key, value);
						}
					});
				}
			});
		},
		submitModuleInfoForm:function(){
			moduleValidator.form();
			if (!moduleValidator.valid()) {
				return false;
			}
			var moduleEditInfo = dwr.util.getFormValues('editModuleForm');
			var moduleInfo4Sub = {};
			$.each(moduleEditInfo, function(key, value) {
				moduleInfo4Sub[key.substring(11,key.length)]=value;
			});
			SysModuleController.moduleInfoSave(moduleInfo4Sub,function(moduleDTO){
				
				if(moduleDTO){
					Message.success("保存成功！");
					initMenuTree(moduleDTO.id);
					moduleInfoView(moduleDTO.id);
				}else{
					Message.erro("保存失败！请刷新页面后重试");
				}
				
			});
		},
		loadMenuInfo4Edit:function(menuId){
			AppUtils.validatorRemoteCache("#editMenu_name");
			SysMenuController.getMenuInfoById(menuId,function(menuInfo){
				if(menuInfo){
					initTabStatus("menu-info-edit","修改菜单");
					AppUtils.clearForm("#editMenuForm");
					$.each(menuInfo, function(key, value) {
						if($("#editMenu_"+key).length){
							if(key == "icon"){
								$("#edit_icon").find("i").attr("class",value);
							}
							if(key == "display"){
								if(value == 1){
									AppUtils.setChecked($("#"+key));
								}
							}
							dwr.util.setValue('editMenu_' + key, value);
						}
					});
				}
			});
		},
		submitMenuInfoForm:function(){
			menuValidator.form();
			if (!menuValidator.valid()) {
				return false;
			}
			var menuEditInfo = dwr.util.getFormValues('editMenuForm');
			var menuInfo4Sub = {};
			$.each(menuEditInfo, function(key, value) {
				if(key.indexOf("display") > -1){
					if(value){
						menuInfo4Sub[key.substring(9,key.length)]=1;
					}else{
						menuInfo4Sub[key.substring(9,key.length)]=0;
					}
				}else{
					menuInfo4Sub[key.substring(9,key.length)]=value;
				}
				
			});
			
			SysMenuController.saveMenuInfo(menuInfo4Sub,function(menuDTO){
				if(menuDTO){
					Message.success("保存成功！");
					initMenuTree(menuDTO.id);
					menuInfoView(menuDTO.id);
				}else{
					Message.erro("保存失败！请刷新页面后重试");
				}
				
			});
		},
		choiceIconDialog:function(){
			DialogUtils.open({
				title: '选择图标',
			    area: ['790px', '380px'],
			    fix: false, //不固定
			    maxmin: true,
			    content: contextPath+'/sys/menu/iconChoice.htm?nowIcon='+$("#editMenu_icon").val(),
			    btn: ['保存', '取消'],
			    yes: function(index, layero){
			    	updateIconText(index,layero);
			    },cancel: function(index){
			    }
			});
		}
			
		
	};
}();